package com.lishuang.user.controller;

import com.lishuang.basic.exception.BusinessException;
import com.lishuang.basic.util.AjaxResult;
import com.lishuang.basic.util.PageList;
import com.lishuang.user.domain.Logininfo;
import com.lishuang.user.domain.User;
import com.lishuang.user.dto.UserDto;
import com.lishuang.user.query.UserQuery;
import com.lishuang.user.service.ILogininfoService;
import com.lishuang.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/user")
@Api(value = "用户API", description = "用户相关的CRUD功能")
public class UserController {

    @Autowired
    public IUserService userService;

    @Autowired
    private ILogininfoService logininfoService;

    /**
     * 接口：添加或修改
     * @param user  传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    @ApiOperation(value = "添加或者修改(通过有无ID区分)")
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null)
                userService.update(user);
            else
                userService.save(user);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return AjaxResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    @ApiOperation(value = "通过ID删除数据")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return AjaxResult 响应给前端
    */
    @PatchMapping
    @ApiOperation(value = "通过ids批量删除数据")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
                userService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    public User findOne(@PathVariable("id")Long id) {
        return userService.loadById(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<User> findAll(){
        return userService.loadAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryPage(query);
    }


    /**
     * 接口：用户手机注册
     * @param userDto
     * @return AjaxResult
     */

    @PostMapping("/phone/register")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        }
        catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("注册失败!"+e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统异常,请稍后重试!");
        }
    }

    /**
     * 接口：用户邮箱注册
     * @param userDto
     * @return AjaxResult
     */

    @PostMapping("/email/register")
    public AjaxResult emailRegister(@RequestBody UserDto userDto){
        try {
            userService.emailRegister(userDto);
            return AjaxResult.me();
        }
        catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("注册失败!"+e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统异常,请稍后重试!");
        }
    }


    /**
     * 邮箱激活
     *
     * @param id
     * @return AjaxResult
     */
    @GetMapping("/email/active/{id}")
    public void active(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
         /*   User user = userService.loadById(id);
            if (user.getState()==0) {
                user.setState(1);
                userService.update(user);
            }
            Logininfo logininfo = logininfoService.loadById(user.getLogininfoId());*/

            //激活跳转，修改logininfo为启用状态
            Logininfo logininfo = logininfoService.loadById(id);
            if (logininfo.getDisable()==false) {
                logininfo.setDisable(true);
                logininfoService.update(logininfo);
            }
            response.getWriter().write("激活成功,3秒后跳转到登录页面。。。");

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("激活失败，请联系管理员。。。");
        }finally {
            response.setHeader("refresh","3;URL='http://localhost/login.html'");
        }

    }


}
